package com.huyun.web.FutureTest.Future;

import lombok.Data;

import java.util.concurrent.*;

@Data
public class FutureTaskTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //第一种方式 Future + ExecutorService
//        ExecutorService service = Executors.newCachedThreadPool();
//        Future<String> ft2 = service.submit(new T2Task());
//        Future<String> ft1 = service.submit(new T1Task((FutureTask) ft2));
//        System.out.println(ft1.get());
//        service.shutdown();

        //第二种方式: FutureTask + ExecutorService
        ExecutorService service = Executors.newCachedThreadPool();
        FutureTask<String> ft2 = new FutureTask<String>(new T2Task());
        FutureTask<String> ft1 = new FutureTask<String>(new T1Task(ft2));
        service.submit(ft2);
        service.submit(ft1);
        service.shutdown();
        //第三种方式:FutureTask + Thread
//        FutureTask<String> ft2 = new FutureTask<>(new T2Task());
//        //执行 T1Task 任务中传入T2Task的返回结果后在执行后续操纵
//        FutureTask<String> ft1 = new FutureTask<>(new T1Task(ft2));
//        Thread t1 = new Thread(ft1);
//        t1.start();
//        Thread t2 = new Thread(ft2);
//        t2.start();
//        System.out.println(ft1.get());

    }
    static class  T1Task implements Callable<String> {
        FutureTask<String> t2;

        public T1Task(FutureTask t2) {
            this.t2 = t2;
        }
        @Override
        public String call() throws Exception {
            System.out.println("T1:洗水壶...");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("T1:烧开水");
            TimeUnit.SECONDS.sleep(15);
            String o = t2.get(); //等待 T2Task 执行完成
            System.out.println("T1拿到茶叶："+o);
            System.out.println("T1:泡茶...");
            return "上茶:" + o;
        }
    }
    static class T2Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("T2:洗茶壶...");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("T2:洗茶杯...");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("T2:拿茶叶...");
            TimeUnit.SECONDS.sleep(1);
            return "龙井";
        }
    }
}
